import { requestClient } from '#/api/request';

/**
 * 限流配置
 */
export interface RateLimitConfig {
  enabled: boolean;
  defaultLimit: number;
  ipLimit: number;
  userLimit: number;
  pathLimits: Record<string, number>;
  whiteList: string[];
}

/**
 * 剩余令牌响应
 */
export interface RemainingTokensResponse {
  key: string;
  remaining: number;
  maxRequests: number;
  windowSeconds: number;
}

/**
 * 限流统计信息
 */
export interface RateLimitStats {
  totalKeys: number;
  ipLimitKeys: number;
  userLimitKeys: number;
  pathLimitKeys: number;
  defaultLimitKeys: number;
}

/**
 * 全局指标
 */
export interface GlobalMetric {
  totalRequests: number;
  allowedRequests: number;
  blockedRequests: number;
  blockRate: number;
}

/**
 * 指标数据
 */
export interface MetricData {
  key: string;
  totalRequests: number;
  allowedRequests: number;
  blockedRequests: number;
  blockRate: number;
  lastAccessTime: string;
}

/**
 * 通用响应
 */
export interface CommonResponse {
  success: boolean;
  message?: string;
  key?: string;
  clearedCount?: number;
}

/**
 * 获取限流配置
 */
export async function getRateLimitConfigApi() {
  return requestClient.get<RateLimitConfig>('/gateway/api/rate-limit/config');
}

/**
 * 查询指定键的剩余令牌数
 */
export async function getRemainingTokensApi(params: {
  key: string;
  maxRequests?: number;
  windowSeconds?: number;
}) {
  return requestClient.get<RemainingTokensResponse>(
    '/gateway/api/rate-limit/remaining',
    {
      params,
    },
  );
}

/**
 * 查询所有限流键
 */
export async function getAllKeysApi() {
  return requestClient.get<string[]>('/gateway/api/rate-limit/keys');
}

/**
 * 清除指定键的限流记录
 */
export async function clearRateLimitApi(key: string) {
  return requestClient.delete<CommonResponse>('/gateway/api/rate-limit/clear', {
    params: { key },
  });
}

/**
 * 清除所有限流记录
 */
export async function clearAllRateLimitApi() {
  return requestClient.delete<CommonResponse>(
    '/gateway/api/rate-limit/clear-all',
  );
}

/**
 * 获取限流统计信息
 */
export async function getRateLimitStatsApi() {
  return requestClient.get<RateLimitStats>('/gateway/api/rate-limit/stats');
}

/**
 * 获取全局指标
 */
export async function getGlobalMetricsApi() {
  return requestClient.get<GlobalMetric>(
    '/gateway/api/rate-limit/metrics/global',
  );
}

/**
 * 获取所有指标
 */
export async function getAllMetricsApi() {
  return requestClient.get<Record<string, MetricData>>(
    '/gateway/api/rate-limit/metrics/all',
  );
}

/**
 * 获取指定键的指标
 */
export async function getMetricApi(key: string) {
  return requestClient.get<MetricData>(
    `/gateway/api/rate-limit/metrics/${key}`,
  );
}

/**
 * 清除所有指标
 */
export async function clearMetricsApi() {
  return requestClient.delete<CommonResponse>(
    '/gateway/api/rate-limit/metrics/clear',
  );
}

// ==================== 限流配置管理 API ====================

/**
 * 限流配置实体
 */
export interface RateLimitConfigEntity {
  id?: number;
  configName: string;
  configType: string; // DEFAULT, IP, USER, PATH
  limitType?: string; // IP, USER, GLOBAL
  pathPattern?: string;
  windowSeconds: number;
  maxRequests: number;
  enabled: boolean;
  whiteList?: string; // IP白名单，JSON数组格式的字符串
  description?: string;
  createTime?: string;
  updateTime?: string;
}

/**
 * 配置验证结果
 */
export interface ValidationResult {
  valid: boolean;
  message: string;
}

/**
 * 分页查询参数（继承实体类，添加分页参数）
 */
export interface RateLimitConfigQueryParams
  extends Partial<RateLimitConfigEntity> {
  pageNum?: number;
  pageSize?: number;
}

/**
 * 分页查询响应（响应拦截器已将MyBatis Plus格式转换为标准格式）
 * 后端返回: { datas: { records, total, current, size, pages }, respCode, respMsg }
 * 响应拦截器转换后: { list, total, pageNum, pageSize }
 */
export interface RateLimitConfigPageResponse {
  list: RateLimitConfigEntity[];
  total: number;
  pageNum: number;
  pageSize: number;
}

/**
 * 分页查询限流配置
 */
export async function getConfigListApi(params?: RateLimitConfigQueryParams) {
  return requestClient.post<RateLimitConfigPageResponse>(
    '/gateway/api/rate-limit/config/list',
    params || {},
  );
}

/**
 * 根据ID查询限流配置
 */
export async function getConfigByIdApi(id: number) {
  return requestClient.get<RateLimitConfigEntity>(
    `/gateway/api/rate-limit/config/${id}`,
  );
}

/**
 * 创建限流配置
 */
export async function createConfigApi(data: RateLimitConfigEntity) {
  return requestClient.post<RateLimitConfigEntity>(
    '/gateway/api/rate-limit/config',
    data,
  );
}

/**
 * 更新限流配置
 */
export async function updateConfigApi(id: number, data: RateLimitConfigEntity) {
  return requestClient.put<RateLimitConfigEntity>(
    `/gateway/api/rate-limit/config/${id}`,
    data,
  );
}

/**
 * 删除限流配置
 */
export async function deleteConfigApi(id: number) {
  return requestClient.delete<CommonResponse>(
    `/gateway/api/rate-limit/config/${id}`,
  );
}

/**
 * 启用/禁用限流配置
 */
export async function updateConfigEnabledApi(id: number, enabled: boolean) {
  return requestClient.put<RateLimitConfigEntity>(
    `/gateway/api/rate-limit/config/${id}/enabled`,
    null,
    {
      params: { enabled },
    },
  );
}

/**
 * 刷新限流配置缓存
 */
export async function refreshConfigApi() {
  return requestClient.post<CommonResponse>(
    '/gateway/api/rate-limit/config/refresh',
  );
}

/**
 * 获取当前生效的限流配置
 */
export async function getCurrentConfigApi() {
  return requestClient.get<RateLimitConfig>(
    '/gateway/api/rate-limit/config/current',
  );
}

/**
 * 批量导入限流配置
 */
export async function batchCreateConfigApi(data: RateLimitConfigEntity[]) {
  return requestClient.post<RateLimitConfigEntity[]>(
    '/gateway/api/rate-limit/config/batch',
    data,
  );
}

/**
 * 配置验证
 */
export async function validateConfigApi(data: RateLimitConfigEntity) {
  return requestClient.post<ValidationResult>(
    '/gateway/api/rate-limit/config/validate',
    data,
  );
}
